import json
from decimal import Decimal

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.OrderInfos.models import OrderInfo, OrderGoods
from apps.products.models import Product
from utils.views import LoginRequiredJsonMixin
from apps.users.models import Address


class OrderSettlementView(View):
    """订单结算"""

    def get(self, request):
        user = request.user
        # 获取当前用户的地址信息
        addresses = Address.objects.filter(user_id=user.user_id, is_deleted=False)
        address_list = []
        for address in addresses:
            address_list.append({
                'id': address.id,
                'province': address.province.name,
                'city': address.city.name,
                'district': address.district.name,
                'receiver': address.receiver,
                'place': address.place,
                'mobile': address.mobile
            })
        # 获取当前用户购物车中的信息
        redis_cli = get_redis_connection('carts')
        product_id_counts = redis_cli.hgetall('cart_%s' % user.user_id)
        selected_ids = redis_cli.smembers('selected_%s' % user.user_id)
        # 获取选中状态的购物车商品
        selected_cart = {}
        for product_id in selected_ids:
            selected_cart[int(product_id)] = int(product_id_counts[product_id])
        product_list = []
        products = Product.objects.filter(product_id__in=selected_cart.keys())
        for product in products:
            product_list.append({
                'id': product.product_id,
                'name': product.product_name,
                'image_url': product.img_url,
                'count': selected_cart[product.product_id],
                'price': product.price,
                'amount': product.price * selected_cart[product.product_id]
            })
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'addresses': address_list,
            'products': product_list
        })


class OrderCommitView(LoginRequiredJsonMixin, View):
    """提交订单"""

    def post(self, request):
        # 1.接收数据
        user = request.user
        data = json.loads(request.body.decode())
        address_id = data.get('address_id')
        pay_method = data.get('pay_method')
        # 2.验证数据
        if not all([address_id, pay_method]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        try:
            address = Address.objects.get(id=address_id)
        except Address.DoesNotExist:
            return JsonResponse({"code": 400, 'errmsg': '没有相应的地址信息'})
        if pay_method not in [OrderInfo.PAY_METHOD_ENUM["WeChat"], OrderInfo.PAY_METHOD_ENUM["Alipay"]]:
            return JsonResponse({"code": 400, 'errmsg': '参数错误'})
        # 生成订单编号  组成：年月日时分秒 用户id
        from django.utils import timezone
        # 获取当前时间将其转换为字符串
        order_id = timezone.localtime().strftime('%Y%m%d%H%M%S') + str(user.user_id)
        total_count = 0
        total_amount = Decimal('0')
        # 3.数据入库
        orderinfo = OrderInfo.objects.create(
            order_id=order_id,
            user_id=user.user_id,
            address_id=address_id,
            total_count=total_count,
            total_amount=total_amount,
            pay_method=pay_method
        )
        # 保存订单里的商品信息
        redis_cli = get_redis_connection('carts')
        product_id_counts = redis_cli.hgetall('cart_%s' % user.user_id)
        selected_ids = redis_cli.smembers('selected_%s' % user.user_id)
        selected_products = {}
        for select_id in selected_ids:
            selected_products[int(select_id)] = int(product_id_counts[select_id])
        for product_id, count in selected_products.items():
            try:
                product = Product.objects.get(product_id=product_id)
            except Product.DoesNotExist:
                return JsonResponse({'code': 400, 'errmsg': '商品id不存在'})
            # 判断商品库存是否充足
            if product.num < count:
                return JsonResponse({'code': 400, "errmsg": product.product_name + '库存不足'})
            product.num -= count
            product.sales += count
            product.save()
            orderinfo.total_count += count
            orderinfo.total_amount += (count * product.price)
            OrderGoods.objects.create(
                order_id=order_id,
                product_id=product_id,
                count=count,
                price=product.price
            )
        orderinfo.save()
        # 清除 redis内已付款的保存的购物车信息
        pl = redis_cli.pipeline()
        pl.hdel('cart_%s' % user.user_id, *selected_ids)
        pl.srem('selected_%s' % user.user_id, *selected_ids)
        pl.execute()

        return JsonResponse({'code': 0, 'errmsg': '购买完成', 'order_id': order_id})


class OrderInfosView(LoginRequiredJsonMixin, View):
    """获取订单信息表数据"""

    def get(self, request):
        # 1.接收参数
        user = request.user
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')
        # 2.数据库中获取数据
        order_infos = OrderInfo.objects.filter(user_id=user.user_id, is_delete=False).order_by(ordering)
        # 分页
        paginator = Paginator(order_infos, per_page=page_size)
        # 获取指定页面的数据
        page_orders = paginator.page(page)
        order_list = []
        for order_info in page_orders.object_list:
            order_list.append({
                'id': order_info.order_id,
                'amount': order_info.total_amount,
                'create_time': order_info.create_time,
                'pay_method': order_info.get_pay_method_display(),
                'status': order_info.get_status_display()
            })
        # 得到总页数
        total_num = paginator.num_pages
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'order_list': order_list, 'count': total_num})


class OrderGoodsView(View):
    """获取订单商品表数据"""

    def get(self, request):
        user = request.user
        order_id = request.GET.get('order_id')
        ordering = request.GET.get('ordering')
        product_list = []
        order_products = OrderGoods.objects.filter(order_id=order_id).order_by(ordering)
        for order_product in order_products:
            product_list.append({
                'count': order_product.count,
                'price': order_product.price,
                'name': order_product.product.product_name,
                'image_url': order_product.product.img_url
            })
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'order_good_list': product_list})


class DeleteOrderInfoView(View):
    """删除已完成订单"""

    def delete(self, request, id):
        try:
            order_info = OrderInfo.objects.get(order_id=id)
            order_info.is_delete = True
            order_info.save()
        except OrderInfo.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '订单不存在'})
        return JsonResponse({'code': 0, 'errmsg': '删除成功'})


class OrderSendInfosView(View):
    """获取待配送订单信息"""

    def get(self, request):
        user = request.user
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')
        status = request.GET.get('status')
        order_infos = OrderInfo.objects.filter(user_id=user.user_id, is_delete=False, status=status).order_by(ordering)
        if not order_infos:
            return JsonResponse({'code': 400, 'errmsg': '暂无待配送订单'})
        paginator = Paginator(order_infos, per_page=page_size)
        # 获取指定页面的数据
        page_orders = paginator.page(page)
        send_orders = []
        for order_info in page_orders.object_list:
            send_orders.append({
                'id': order_info.order_id,
                'amount': order_info.total_amount,
                'create_time': order_info.create_time,
                'pay_method': order_info.get_pay_method_display(),
                'status': order_info.get_status_display()
            })
        total_num = paginator.num_pages
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'send_orders': send_orders, 'count': total_num})


class OrderSendGoodsView(View):
    """获取待配送订单的商品信息"""

    def get(self, request):
        user = request.user
        order_id = request.GET.get('order_id')
        ordering = request.GET.get('ordering')
        send_list = []
        order_products = OrderGoods.objects.filter(order_id=order_id).order_by(ordering)
        for order_product in order_products:
            send_list.append({
                'count': order_product.count,
                'price': order_product.price,
                'name': order_product.product.product_name,
                'image_url': order_product.product.img_url
            })
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'send_good_list': send_list})


class FinishOrdersView(View):
    """获取已完成订单信息"""

    def get(self, request):
        user = request.user
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')
        status = request.GET.get('status')
        order_infos = OrderInfo.objects.filter(user_id=user.user_id, is_delete=False, status=status).order_by(ordering)
        if not order_infos:
            return JsonResponse({'code': 400, 'errmsg': '暂无已完成订单'})
        paginator = Paginator(order_infos, per_page=page_size)
        # 获取指定页面的数据
        page_orders = paginator.page(page)
        finish_orders = []
        for order_info in page_orders.object_list:
            finish_orders.append({
                'id': order_info.order_id,
                'amount': order_info.total_amount,
                'create_time': order_info.create_time,
                'pay_method': order_info.get_pay_method_display(),
                'status': order_info.get_status_display()
            })
        total_num = paginator.num_pages
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'finish_orders': finish_orders, 'count': total_num})


class FinishGoodsView(View):
    """获取已完成订单的商品信息"""

    def get(self, request):
        user = request.user
        order_id = request.GET.get('order_id')
        ordering = request.GET.get('ordering')
        finish_list = []
        order_products = OrderGoods.objects.filter(order_id=order_id).order_by(ordering)
        for order_product in order_products:
            finish_list.append({
                'count': order_product.count,
                'price': order_product.price,
                'name': order_product.product.product_name,
                'image_url': order_product.product.img_url
            })
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'finish_good_list': finish_list})


class RefundOrdersView(View):
    """获取已完成订单信息"""

    def get(self, request):
        user = request.user
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')
        status = request.GET.get('status')
        order_infos = OrderInfo.objects.filter(user_id=user.user_id, is_delete=False, status=status).order_by(ordering)
        if not order_infos:
            return JsonResponse({'code': 400, 'errmsg': '暂无取消的订单'})
        paginator = Paginator(order_infos, per_page=page_size)
        # 获取指定页面的数据
        page_orders = paginator.page(page)
        refund_orders = []
        for order_info in page_orders.object_list:
            refund_orders.append({
                'id': order_info.order_id,
                'amount': order_info.total_amount,
                'create_time': order_info.create_time,
                'pay_method': order_info.get_pay_method_display(),
                'status': order_info.get_status_display()
            })
        total_num = paginator.num_pages
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'refund_orders': refund_orders, 'count': total_num})


class RefundGoodsView(View):
    """获取已完成订单的商品信息"""

    def get(self, request):
        user = request.user
        order_id = request.GET.get('order_id')
        ordering = request.GET.get('ordering')
        refund_list = []
        order_products = OrderGoods.objects.filter(order_id=order_id).order_by(ordering)
        for order_product in order_products:
            refund_list.append({
                'count': order_product.count,
                'price': order_product.price,
                'name': order_product.product.product_name,
                'image_url': order_product.product.img_url
            })
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'refund_good_list': refund_list})


class CancelOrderView(View):
    """取消订单"""
    def put(self,request):
        data = json.loads(request.body.decode())
        order_id = data.get('order_id')
        try:
            order = OrderInfo.objects.get(order_id=order_id)
        except OrderInfo.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '该订单不存在'})
        order.status = 4
        order.save()
        return JsonResponse({'code': 0, 'errmsg': '取消成功'})